package com.leyou.cart.controller;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.service.CartService;
import com.leyou.common.auth.entity.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping
public class CartController {

    @Autowired
    private CartService cartService;

    //在购物车添加商品
    @PostMapping
    public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
        cartService.addCart(cart);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //查询用户购物车
    @GetMapping("/list")
    public ResponseEntity<List<Cart>> queryCartList() {
        Long userId = UserHolder.getUserId();
        return ResponseEntity.ok(cartService.queryCartList(userId));
    }

    //将本地缓存的购物车单,存到用户购物车中
    @PostMapping("/list")
    public ResponseEntity<Void> addCarts(@RequestBody List<Cart> carts) {
        cartService.addCarts(carts);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //修改购物车信息
    @PutMapping
    public ResponseEntity<Void> updateNum(@RequestParam("id") Long id, @RequestParam("num") Integer num) {
        cartService.updateNum(id, num);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    //删除购物车信息
    @DeleteMapping("{skuId}")
    public ResponseEntity<Void> deleteCart(@PathVariable("skuId")Long skuId) {
        cartService.deleteCart(skuId);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
